# encoding: utf-8

class Admin::SnsController< Admin::ApplicationController
  layout 'admin'

  def index
    @sns_type = params[:t] || :Weibo
    @sns_users = Utility.const_get(@sns_type.capitalize).all #.page(params[:page] || 1)
  end

  def new

  end

  def auto_access
    unless ['weibo', 'tencent'].include? params[:t].downcase
      render_msg :type => :error, :msg => "没有到这种社交网络吧! (╯‵□′)╯︵┻━┻ "
      return
    end
    render_msg :type => :success,
               :msg => "开始自动授权:#{Account.auto_accessing((params[:t].downcase || 'weibo'), params[:ids])}"
  end

  def keep_access
    @sns_type = params[:t] || :Weibo
    Utility.const_get(@sns_type.capitalize).where(:_id.in => params[:ids]).each do |sns_user|
      sns_user.auto_access
    end
    render_msg :type => :success, :msg => "授权成功"
  end

  def destroy
    @sns_type = params[:t] || :Weibo
    Utility.const_get(@sns_type.capitalize).where(:_id.in => params[:ids]).destroy_all
    render_msg :type => :success, :msg => "删除成功"
  end

  def stop
    @sns_type = params[:t] || :Weibo
    Utility.const_get(@sns_type.capitalize).where(:_id.in => params[:ids]).each{|sns_user| sns_user.status['login'] = false;sns_user.save}
    render_msg :type => :success, :msg => "停用成功"
  end

  def revive
    @sns_type = params[:t] || :Weibo
    Utility.const_get(@sns_type.capitalize).where(:_id.in => params[:ids]).each{|sns_user| sns_user.login}
    render_msg :type => :success, :msg => "恢复成功"
  end

  def create
    unless ['Weibo', 'Tencent'].include? params[:t].to_s
      render_msg :type => :error, :msg => "没有到这种社交网络吧! (╯‵□′)╯︵┻━┻ "
      return
    end
    success = 0
    failed  = 0
    updated = 0
    params[:users].split("\n").each do |line|
      spammer = line.split(';')
      if wu = Utility.const_get(params[:t].capitalize).where(:username => spammer[0]).first
        wu.update_attributes(
          :username => spammer[0],
          :password => spammer[1],
          :uid      => spammer[2],
          :access_token => spammer[3] || wu.access_token
          )
        updated += 1
      else
        Utility.const_get(params[:t].capitalize).create(
          :username => spammer[0],
          :password => spammer[1],
          :uid      => spammer[2],
          :access_token => spammer[3]
          )
        success += 1
      end
    end
    render_json :success, "成功添加#{success}个, 更新#{updated}个, 失败#{failed}个."
  end

end